package thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**线程池*/
public class ThreadPoolDemo {
    public static void main(String[] args) {
        // 创建一个线程池，固定线程数
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        for(int i=0;i<5;i++){
            Runnable r=new Runnable(){
                public void run(){
                    // 线程池中的线程执行任务
                    Thread t=Thread.currentThread();
                    System.out.println(t+"正在执行任务...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(t+"执行任务完毕！");
                }
            };
//            Thread t=new Thread(r);
//            t.start();
            threadPool.execute(r);
            System.out.println("将一个任务交给了线程池");
        }
        threadPool.shutdown();//不在继续接受任务，现有任务结束完才停止
        //threadPool.shutdownNow();//立刻停止，并清空所有线程
        System.out.println("线程池关闭了");
    }
}
